import { useEffect, useState } from 'react'

const useResizeObserver = (ref: any) => {
  const [dimensions, setDimensions] = useState({})

  useEffect(() => {
    const observer = new ResizeObserver((entries) => {
      const { width, height } = entries[0].contentRect
      setDimensions(() => {
        const dimensionsObj = { width, height }
        return dimensionsObj
      })
      // console.log('width,height', width, height, dimensions)
    })
    if (ref.current) {
      observer.observe(ref.current)
    }
    return () => {
      if (ref.current) {
        observer.unobserve(ref.current)
      }
    }
  }, [ref])

  return dimensions
}

export default useResizeObserver
